<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;

/**
 * 微信应用接口
 */
class Wechat extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 首页
     *
     */
    public function index()
    {
        //获取分类数据
        $model = model("category");
        $result = array("status" => 200, "msg" =>"ok","data"=>[]);

        $list = $model->where("status='normal'")->field("id,name,image,type,flag,menu")->select();
        //拼接前端跳转地址 1 维修教程 维修案例 2 我的收藏 3 备件检索
        foreach ($list as &$vv){
            if($vv["menu"] == 1){
                $vv["pageUrl"] = "/pages/lists/lists?cid={$vv['id']}&cname={$vv['name']}";
            }elseif ($vv["menu"] == 2){
                $vv["pageUrl"] = "/pages/collect/collect";
            }else if($vv["menu"] == 3){
                $vv["pageUrl"] = "/pages/coperion/coperion";
            }else{
                $vv["pageUrl"] = "";
            }
        }


        if($list){
            $result["data"] = $list;
            return json($result);
        }else{
            $result["status"] = 2020;
            $result["msg"] = "暂无数据";
            return json($result);
        }


    }

    /*
     * 获取小程序授权logo 提前配置在数据库 或者 配置文件
     *
     */
    public function get_logo()
    {
        $config = config("routine");
        $routine_logo=$config['routine_logo'];
        $result = array("status" => 200, "msg" =>"ok","data"=>[]);

        if($routine_logo){
            $result["data"]["logo_url"] = $routine_logo;
            return json($result);
        }else{
            $result["status"] = 2020;
            $result["msg"] = "暂无数据";
            return json($result);
        }


    }


    public function test(){
        $post_cache_key = "jiashaowei";
        $session_key = Cache::set('eb_api_code_'.$post_cache_key,300);
        print_r($session_key);

    }

    public function test2(){
        $post_cache_key = "jiashaowei";
        $session_key = Cache::get('eb_api_code_'.$post_cache_key);
        print_r($session_key);
    }

    /*
 * 小程序授权登录
 * @param json
 *
 * */
    public function mp_auth()
    {
        $result = array("status" => 200, "msg" => "ok", "data" => []);
        $params = $this->request->post();

        vendor('smwechat.WXBizDataCrypt');
        vendor('smwechat.ErrorCode');

        $appid = config('routine')["routine_base"]["routine_appId"];
        $appsecret = config('routine')["routine_base"]["routine_appsecret"];
        $grant_type = "authorization_code"; //授权（必填）

        $encryptedData = $params['encryptedData'];
        $iv = $params['iv'];
        $signature = $params['signature'];
        $rawData = $params['rawData'];

        $post_cache_key = array_key_exists("cache_key", $params) ? $params["cache_key"] : '';

        $session_key = Cache::get('small_api_code_' . $post_cache_key);


        if ($session_key) {
            //存在sessionkey 就不校验签名的合法性 直接解密 减少请求

            $pc = new \WXBizDataCrypt($appid, $session_key);
            $errCode = $pc->decryptData($encryptedData, $iv, $wxdata);
            if ($errCode == 0) {
                //执行数据库操作
                $r = $this->findUser($wxdata);
                if ($r > 0) {
                    $resinfo["token"] = "";
                    $resinfo["userInfo"] = $r;
                    $resinfo["uid"] = $r;
                    $resinfo["expires_time"] = 0;
                    $result["data"] = $resinfo;
                } else {
                    $result["status"] = 2020;
                    $result["msg"] = "添加失败";
                }
                return json($result);
            } else {
                $result["status"] = 2020;
                $result["msg"] = $errCode;
                return json($result);
            }
        }


        $code = $params["code"]["code"];    //有效期5分钟 登录会话

        if (!$code && !$session_key) {
            $result["status"] = 2020;
            $result["msg"] = "授权失败,参数有误";
            return json($result);
        }

        if ($code && !$session_key) {
            try {
                //用户自行缓存sessionkey 具有接口请求次数限制，只有sessionkey未过期 就不用请求接口
                $url = "https://api.weixin.qq.com/sns/jscode2session?" . "appid=" . $appid . "&secret=" . $appsecret . "&js_code=" . $code . "&grant_type=" . $grant_type;
                $res = json_decode($this->httpGet($url), true);
                $sessionKey = $res['session_key']; //取出json里对应的值
                $signature2 = sha1(htmlspecialchars_decode($rawData) . $sessionKey);
                if ($signature2 !== $signature) {
                    $result["status"] = 2020;
                    $result["msg"] = "验签失败";
                    return json($result);
                }
                //缓存key 12个小时
                $cache_key = md5(time() . $code);
                Cache::set('small_api_code_' . $cache_key, $sessionKey, 43200);

                // 获取解密后的数据
                $pc = new \WXBizDataCrypt($appid, $sessionKey);
                $errCode = $pc->decryptData($encryptedData, $iv, $wxdata);

                if ($errCode == 0) {
                    //执行数据库操作
                    $r = $this->findUser($wxdata);

                    if ($r > 0) {
                        $resinfo["token"] = "";
                        $resinfo["userInfo"] = $r;
                        $resinfo["uid"] = $r;
                        $resinfo["expires_time"] = 0;
                        $resinfo["cache_key"] = $cache_key;
                        $result["data"] = $resinfo;
                    } else {
                        $result["status"] = 2020;
                        $result["msg"] = "添加失败";
                    }
                    return json($result);

                } else {
                    $result["status"] = 2020;
                    $result["msg"] = $errCode;
                    return json($result);

                }

            } catch (\Exception $e) {
                $result["status"] = 2020;
                $result["msg"] = $e->getMessage();
                return json($result);

            }
        }

    }


    /*
     * 小程序授权登录
     * @param json
     *
     */
    public function auth_login(){
        // 接收参数
        $data = request() -> param();
        $result = array("status" => 200, "msg" => "ok", "data" => []);

        // 引入解密文件 在微信小程序开发文档下载
        vendor('smwechat.WXBizDataCrypt');
        vendor('smwechat.ErrorCode');

        $appid = config('routine')["routine_base"]["routine_appId"];
        $appsecret = config('routine')["routine_base"]["routine_appsecret"];
        $grant_type = "authorization_code"; //授权（必填）
        $code = $data['code'];        //有效期5分钟 登录会话

        $encryptedData=$data['encryptedData'];
        $iv = $data['iv'];
        $signature = $data['signature'];
        $rawData = $data['rawData'];

        // 拼接url
        $url = "https://api.weixin.qq.com/sns/jscode2session?"."appid=".$appid."&secret=".$appsecret."&js_code=".$code."&grant_type=".$grant_type;
        $res = json_decode($this->httpGet($url),true);


        $sessionKey = $res['session_key']; //取出json里对应的值
        $signature2 =  sha1(htmlspecialchars_decode($rawData).$sessionKey);
        // 验证签名
        if ($signature2 !== $signature){
            return json("验签失败");
        }

        // 获取解密后的数据
        $pc = new \WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            //执行数据库操作
            $ressql = $this->findUser($data);
            if($ressql){
                $result["data"] = $ressql;
                return json($result);
            }else{
                $result["status"] = 2020;
                $result["msg"] = "插入数据错误";
                return json($result);
            }

        } else {
            $result["status"] = 2020;
            $result["msg"] = $errCode;
            return json($result);
        }
    }

    //添加用户
    public function findUser($info){
        $info  = json_decode($info,true);
        $model =  model("user");
        $where["openId"] = $info["openId"];
        $res = $model->where($where)->field("id,nickname,avatar,openId")->find();

        if($res){
           return $res;
        }else{
            $data["group_id"] = 2;//固定用户组
            $data["from"] = 2;//固定来源
            $resdata["nickname"] = $data["nickname"] = $info["nickName"];
            $resdata["avatar"] = $data["avatar"] =  $info["avatarUrl"];
            $data["gender"] = $info["gender"];
            $data["createtime"] = time();
            $data["status"] = "normal";
            $data["country"] = $info["country"];
            $data["province"] = $info["province"];
            $data["city"] = $info["city"];
            $resdata["openId"] = $data["openId"] = $info["openId"];
            $insertId = $model->insertGetId($data);
            $resdata["id"] = $insertId;

            if($insertId){
                return $resdata;
            }else{
                return [];
            }
        }

    }

    //get 请求
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }


}
